package com.liy.framework.common.logs.task;

import ch.qos.logback.classic.spi.ILoggingEvent;
import com.liy.framework.common.logs.appender.MongodbAppender;
import com.mongodb.BasicDBObject;
import java.util.Map;

public class MongodbLogTask implements Runnable {
    private ILoggingEvent event;

    public MongodbLogTask(ILoggingEvent event) {
        this.event = event;
    }

    public void run() {
        BasicDBObject doc = new BasicDBObject();
        String level = this.event.getLevel().toString();
        doc.append("level", level);
        doc.append("logger", this.event.getLoggerName());
        doc.append("thread", this.event.getThreadName());
        doc.append("message", this.event.getFormattedMessage());
        doc.append("timestamp", this.event.getTimeStamp());
        if (this.event.getCallerData() != null && this.event.getCallerData().length > 0) {
            StackTraceElement st = this.event.getCallerData()[0];
            String callerData = String.format("%s.%s:%d", st.getClassName(), st.getMethodName(), st.getLineNumber());
            doc.append("caller_info", callerData);
        }

        Map<String, String> mdc = this.event.getMdc();
        if (mdc != null && !mdc.isEmpty()) {
            doc.append("mdc", new BasicDBObject(mdc));
        }

        MongodbAppender.mongoTemplate.insert(doc, "log_" + level);
    }
}
